package com.eeepay.eeepay_v2.util;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.v2_library.log.LogUtils;

import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

/**
 * Created by zw on 2016/3/25 0025.
 * Grpc网络请求工具类
 */
public class GrpcUtils {

    private static GrpcUtils instance;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(MyApplication.context,
                    MyApplication.context.getResources().getString(R.string.network_timeout),
                    Toast.LENGTH_SHORT).show();
        }
    };

    public static GrpcUtils getInstance() {
        if (instance == null) {
            instance = new GrpcUtils();
        }
        return instance;
    }

    /**
     * Grpc异步请求方法
     *
     * @param listener 监听（包括后台线程和前端线程的执行方法）
     * @param taskId   网络请求Id
     */
    public void doGrpcTask(String url, String port, int taskId, AsyncTaskListener listener) {
        LogUtils.d("TAG", "url = " + url + "\nport = " + port);
        new GrpcTask(listener, taskId).execute(url, port);
    }

    /**
     * 异步处理类
     */
    private class GrpcTask extends AsyncTask<String, String, Object> {

        private ManagedChannel mChannel;
        private AsyncTaskListener listener;
        private int taskId;

        public GrpcTask(AsyncTaskListener listener, int taskId) {
            this.listener = listener;
            this.taskId = taskId;
        }


        @Override
        protected Object doInBackground(String... params) {

            try {
                mChannel = ManagedChannelBuilder.forAddress(params[0], Integer.parseInt(params[1]))
                        .usePlaintext(true)
                        .build();
                if (listener != null) {
                return listener.doInBack(mChannel, taskId);
            }
            } catch (Exception e) {
                 /** 在Android中不允许Activity里新启动的线程访问该Activity里的UI组件，这样会导致新启动的线程无法改变UI组件的属性值。**/
                new Runnable() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(0);
                    }
                }.run();
                LogUtils.d("TAG", "background exception = " + e);
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            LogUtils.d("TAG", "onPostExecute  result = " + result);
            try {
                if (mChannel != null && !mChannel.isShutdown())
                    mChannel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {

                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
            if (listener != null) {
                listener.updateUI(result, taskId);
            }
        }
    }

    public interface AsyncTaskListener {
        Object doInBack(ManagedChannel channel, int taskId);

        void updateUI(Object result, int taskId);
    }
}
